package com.hadwinling.binarysearchnorecursion;

/**
 * @author HadwinLing
 * @version V1.0
 * @Package com.hadwinilng.binarysearchnorecursion
 * @date 2020/8/2 10:37
 */
public class BinarySearchNoRecursion {
    public static void main(String[] args) {
        int[] arr = {1,3, 8, 10, 11, 67, 100};
        int index = binarySearch(arr, 100);
        System.out.println("index=" + index);//
    }

    /**
     *
     * 二分法查找的非递归实现 arr是升序排序
     * @param arr 待查找的数组
     * @param target    需要查找的数
     * @return  返回对应下表，-1便是没有找到
     */
    public static int binarySearch(int[] arr,int target){
        int left = 0;
        int right = arr.length-1;
        while (left<=right){//说明继续查找
            int mid =(left+right)/2;
            if (arr[mid] ==target){
                return mid;
            }else if (arr[mid]>target){
                right = mid-1;//需要想左边查找
            }else {
                left = mid+1;//需要向右边查找
            }
        }
        return -1;//没有找到

    }
}
